<template>
  <el-tabs type="border-card">
    <el-tab-pane label="商品基本信息">
      <el-form :model="dataForm" ref="ruleForm" label-width="150px" class="demo-ruleForm">
        {{dataForm}}
        <el-form-item label="商品分类">
          <el-select v-model="dataForm.goods.category1Id" placeholder="请选择一级分类" style="width:27%">
            <el-option
              v-for="item in categorys1"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="dataForm.goods.category2Id" placeholder="请选择二级分类" style="width:27%">
            <el-option
              v-for="item in categorys2"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="dataForm.goods.category3Id" placeholder="请选择三级分类" style="width:27%">
            <el-option
              v-for="item in categorys3"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          {{dataForm.goods.typeTemplateId}}
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="dataForm.goods.goodsName" style="width:81%"></el-input>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="dataForm.goods.brandId" placeholder="请选择品牌" style="width:81%">
            <el-option
              v-for="item in brands"
              :key="item.id"
              :label="item.text"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="副标题">
          <el-input v-model="dataForm.goods.caption" style="width:81%"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="dataForm.goods.price" style="width:81%"></el-input>
        </el-form-item>
        <el-form-item label="商品介绍">
          <el-input type="textarea" v-model="dataForm.goodsDesc.introduction" style="width:81%"></el-input>
        </el-form-item>
        <el-form-item label="包装列表">
          <el-input type="text" v-model="dataForm.goodsDesc.packageList" style="width:81%"></el-input>
        </el-form-item>
        <el-form-item label="售后服务">
          <el-input type="text" v-model="dataForm.goodsDesc.saleService" style="width:81%"></el-input>
        </el-form-item>
      </el-form>

    </el-tab-pane>
    <el-tab-pane label="商品图片">
      <el-button type="warning" @click="newPic" plain size="mini">新建</el-button>

      <el-table
        :data="dataForm.goodsDesc.itemImages"
        style="width: 100%">
        <el-table-column
          prop="color"
          label="颜色"
          align="center">
        </el-table-column>
        <el-table-column
          align="center"
          label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.url" width="100" height="100">
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="dataForm.goodsDesc.itemImages.splice(scope.$index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-tab-pane>
    <el-tab-pane label="扩展属性">
      <el-form label-width="150px" class="demo-ruleForm">
        <el-form-item :label="cust.text" v-for="(cust,index) in dataForm.goodsDesc.customAttributeItems" :key="index">
          <el-input type="text" v-model="cust.value" style="width:81%"></el-input>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <el-tab-pane label="规格">
      <el-table
        :data="specificationItems"
        style="width: 100%">
        <el-table-column
          width="100">
          <template slot-scope="scope">
            {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-checkbox-group v-model="optionList[scope.$index]" size="mini" @change="getOptionList(scope.row.text)">
              <el-checkbox :label="option.optionName" v-for="option in scope.row.options" :key="option.id" border ></el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>
      </el-table>
      <!--sku商品列表-->
      <el-table
        :data="dataForm.items"
        style="width: 100%">
        <el-table-column
          v-for="(spec,key) in dataForm.goodsDesc.specificationItems"
          :label="spec.attributeName"
          align="center"
          :key="key">
          <template slot-scope="scope">
            {{scope.row.spec[spec.attributeName]}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="价格">
          <template slot-scope="scope">
            <el-input v-model="scope.row.price"/>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="数量">
          <template slot-scope="scope">
            <el-input v-model="scope.row.num"/>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>

    <el-button type="primary" @click="save()"  size="small" icon="el-icon-edit-outline" style="margin-top: 10px;">保存</el-button>
    <el-button type="warning"  size="small" icon="el-icon-share">返回列表</el-button>

    <el-dialog title="上传商品图片" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="imageEntity">
        {{imageEntity}}
        <el-form-item label="颜色" label-width="100px">
          <el-input v-model="imageEntity.color" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" label-width="100px">
          <el-upload
            drag
            class="upload-demo"
            :file-list="fileList"
            :http-request="uploadFile"
            list-type="picture">
            <!--<el-button size="small" type="primary">点击上传</el-button>-->
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPic">确 定</el-button>
      </div>
    </el-dialog>
  </el-tabs>
</template>

<script>
  export default {
    data() {
      return {
        visible: false,
        dataForm: {
          goods: {typeTemplateId: ''},      // spu
          goodsDesc: {itemImages: [], customAttributeItems: [], specificationItems: []},  // spu商品描述
          items: []                         // sku列表
        },
        specificationItems:[],    // 代表规格及规格选项列表
        categorys1: [],           // 一级分类
        categorys2: [],           // 二级分类
        categorys3: [],           // 三级分类
        brands: [],               // 根据三级分类得到的品牌列表
        dialogFormVisible: false, // 对话框是否显示的变量
        imageEntity: {},          // 当前上传的图片
        fileList: [],             // 上传的图片列表
        dataRule: {},
        optionList:[],            // 选中项的值数组
        specNames:[],             // 得到选中的规格名字数组
      }
    },
    created() {
      //1. 查询出一级分类
      this.findCategorys1();
    },
    computed: {
      //1. 如果一级分类的值发生变化，此时变量category1Idnew会重新计算,此时可以使用watch来监控这个值的变化
      // category1Idnew() {
      //   return this.dataForm.goods.category1Id;
      // },
      //2. 如果二级分类的值发生变化，此时变量category2Idnew会重新计算,此时可以使用watch来监控这个值的变化
      // category2Idnew() {
      //   return this.dataForm.goods.category2Id;
      // },
      //2. 如果三级分类的值发生变化，此时变量category2Idnew会重新计算,此时可以使用watch来监控这个值的变化
      category3Idnew() {
        return this.dataForm.goods.category3Id;
      },

    },
    watch: {
      //1. 当category1Id的值发生变化时，会加载二级分类
      'dataForm.goods.category1Id'(newV, oldV){      // newV：代表最后选择的一级分类id
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${newV}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categorys2 = data.list
            console.log("data:", data)
          } else {
            this.categorys2 = []
          }
        })
      },
      //2. 当category1Id的值发生变化时，会加载二级分类
      'dataForm.goods.category2Id'(newV, oldV) {      // newV：代表最后选择的一级分类id
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${newV}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categorys3 = data.list
            console.log("data:", data)
          } else {
            this.categorys3 = []
          }
        })
      },
      //3. 当category3Id的值发生变化时，会导致模板id的值发生变化
      category3Idnew(newV, oldV) {      // newV：代表最后选择的一级分类id
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/info/${newV}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataForm.goods.typeTemplateId = data.itemCat.typeId
          }
        })
      },
      //4. 当dataForm.goods.typeTemplateId的值发生变化时，会做如下几件事情：
      // ① 导致品牌列表发生变化，更新品牌列表
      // ② 扩展属性列表发生变化。
      // ③ 规格列表发生变化。
      'dataForm.goods.typeTemplateId'(newV,oldV){   // newV: 代表新的模板id值
        //4.1 查询品牌列表
        this.$http({
          url: this.$http.adornUrl(`/shop/typetemplate/info/${newV}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            // ① 得到品牌列表
            this.brands = JSON.parse(data.typeTemplate.brandIds)
            // ② 得到自定义扩展属性列表
            this.dataForm.goodsDesc.customAttributeItems = JSON.parse(data.typeTemplate.customAttributeItems)
            //4.2 根据模板查询规格列表
            this.$http({
              url: this.$http.adornUrl(`/shop/specification/findSpecList/${newV}`),
              method: 'get',
            }).then(({data}) => {
              if (data && data.code === 0) {
                console.log("spec-data:",data)
                this.specificationItems = data.list;
                // this.optionList这个变量代表用户点击并勾选了规格选项值后的数组，它是一个二维数组，其中二维数组的长度个数由规格的个数值决定。
                data.list.forEach(r=>{
                  this.optionList.push([])        // 为规格选项赋值
                  this.specNames.push(r.text);    // 为规格名称数组赋值
                } )

              }
            })
          }
        })

      }
    },
    methods: {
      //1. 查询出一级分类
      findCategorys1() {
        this.$http({
          url: this.$http.adornUrl('/shop/itemcat/findByParentId/0'),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categorys1 = data.list
            console.log("data:", data)
          } else {
            this.categorys1 = []
          }
        })
      },
      //2. 完成文件上传
      uploadFile(v){
        //2.1 定义表单数据
        let data = new FormData();
        data.append("file",v.file)      // 添加文件对象
        //2.2 清空文件列表
        this.fileList = [];
        //2.3 开始文件上传
        this.$http({
          url: this.$http.adornUrl('/shop/upload'),
          method: 'post',
          data:data,
          headers:{'Content-Type': 'multipart/form-data' },

        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("url:",data.url)
            this.fileList.push({"name":v.raw,'url':data.url})
            this.imageEntity.url = data.url
          }
        })
      },
      //3. 将上传的图片放到dataFrom.goodsDesc.itemImages下并关闭对话框
      addPic(){
        this.dataForm.goodsDesc.itemImages.push(this.imageEntity)
        this.dialogFormVisible = false
      },
      //4. 点击新建按钮
      newPic(){
        //4.1 打开对话框
        this.dialogFormVisible = true;
        //4.2 将上次上传的图片清空
        this.imageEntity = {}
        //4.3 清空文件列表
        this.fileList = []
      },
      //5. 获取规格选项的值
      getOptionList(v){

        // [{"attributeName":"网络制式","attributeValue":["移动3G","移动4G"]},
        //   {"attributeName":"屏幕尺寸","attributeValue":["6寸","5寸"]}]
        // console.log("getOptionList:",this.optionList);
        let specList = [];
        //5.1 遍历规格选项，为specificationItems赋值
        for (let i = 0;i < this.optionList.length;i++){
          specList.push({attributeName:this.specNames[i],attributeValue:this.optionList[i]})
        }
        //5.2 将当前规格列表specList赋值给this.dataForm.goodsDesc.specificationItems
        // 其中,当某个规格一个都未选中时的情况处理,使用过滤器处理一下
        this.dataForm.goodsDesc.specificationItems=specList.filter(f=>f.attributeValue.length > 0);

        //5.3 创建规格列表表格的数据
        this.createSpecList()
        console.log(specList)

      },
      // 6. 动态构造sku商品列表的数据
      createSpecList(){
        //1. 定义默认的sku商品列表
        this.dataForm.items = [{spec:{},price:0,num:9999,status:'0',isDefault:'0'}];  // spec: 代表规格，类似：{"机身内存":"128G","网络":"电信4G"}
        //2. 得到用户选择的规格列表
        let items = this.dataForm.goodsDesc.specificationItems;
        //3. 如果有值，就动态向this.dataForm.items中添加内容
        if(items && items.length > 0){
          items.forEach(item=>{
            this.dataForm.items = this.addColumn(this.dataForm.items,item.attributeName,item.attributeValue)
          })
        }
      },
      //7. 添加一条数据
      addColumn(items,attName,attValue){
        //7.1 定义一个临时存放规格的数组
        let spList = [];
        //7.2 遍历items向spList放数据
        items.forEach(item=>{
          attValue.forEach(value=>{
            //7.2.1 构造一个新行(深克隆完成)
            let newItem = JSON.parse(JSON.stringify(item));
            //7.2.2 为新行赋值
            newItem.spec[attName] = value
            //7.2.3 向新数组添加内容
            spList.push(newItem);
          })
        })
        return spList;
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      }
    }
  }
</script>
